const db = require('../db/index.js')
const _ = require('lodash')

function getTree(arr, type) {
    let arrTree = []
    for (var i in arr) {
        if (arr[i]['cat_level'] == 0) {
            arrTree.push(arr[i])
        } else {
            if (arr[i]['cat_level'] > type) continue;

            let parentId = arr[i]['cat_pid']
            let parent = arr[parentId]
                // console.log(parent.children)
            if (!parent) continue;
            if (!parent.children) {
                parent.children = []
            }
            parent.children.push(arr[i])
        }
    }
    return arrTree;
}
exports.getAllCategories = (req, res) => {
    let { type, pagesize, pagenum } = req.query;
    type = type ? 3 : type;
    let sql1 = 'select * from sp_category  '
    db.query(sql1, (err, results) => {
        var obj = {
            data: {},
            meta: {
                status: '',
                msg: ''
            }
        }
        if (err) {
            obj.meta.status = 500;
            obj.meta.msg = '数据库查询错误';
            return res.send(obj);
        } else {
            let arr = _.keyBy(results, function(o) { //arr实际是一个对象的格式      {}
                return o.cat_id;
            });
            console.log(arr)
            let arrTree = getTree(arr, type)
            if (pagesize && pagenum) {
                obj.data.total = arrTree.length;
                obj.data.pagesize = pagesize;
                obj.data.pagenum = pagenum;
                let arr1 = _.drop(arrTree, (pagenum - 1) * pagesize) //把前面页面数据去除
                let arr2 = _.take(arr1, pagesize); //一共读取几条
                obj.data.result = arr2;
            } else {
                obj.data = arrTree
            }
            obj.meta.status = 200;
            obj.meta.msg = '数据库查询成功';
            return res.send(obj);
        }
    })

}